import { Idb } from '../db'
import { FilesService, FilesModel, IFiles } from './files'
import { ArticleModel, ArticleService, IArticle } from './article'

class Result<T = any> {
  code: number = 0
  data?: T
  msg?: string | object = ''

  constructor(opt: Result = {} as Result) {
    Object.assign(this, opt)
  }
}

interface ICache {
  db: Idb
  filesService: FilesService
  articleService: ArticleService
}

class Services {
  public cache: ICache
  constructor(opt: ICache) {
    this.cache = opt
  }

  /** 添加文件， 文件夹 */
  public async addFile(data: IFiles) {
    let file = await this.getFile(data.name)

    if (file?.code && file.data) {
      return new Result({ code: 0, msg: data.name + '文件已存在' })
    }

    let res: Result = new Result()
    if (data.type === 'file') {
      res = await this.cache.articleService.addArticle({})

      if (res.code) {
        data.article_id = res.data

        return await this.cache.filesService.push(data)
      }
    } else {
      return await this.cache.filesService.push(data)
    }

    return res
  }
  async getFile(key: string | number) {
    if (typeof key === 'string') {
      return await this.cache.filesService.findByIndex(key)
    } else if (typeof key === 'number') {
      return await this.cache.filesService.findById(key)
    }
  }
  async findAll() {
    return await this.cache.filesService.findAll()
  }
  async updataFile(data: any) {
    return await this.cache.filesService.updata(data as FilesModel, data.id)
  }
  async deleteFile(id: number, aid: number) {
    let file = await this.cache.filesService.delete(id)
    let art = await this.cache.articleService.delete(aid)
    return new Result({
      code: (file.code && art.code) || 0
    })
  }
  /** 获取文章 */
  async getArticle(id: number) {
    return await this.cache.articleService.findById(id)
  }
  /** 更新文章 */
  async updateArticle(data: IArticle) {
    return await this.cache.articleService.updata(data)
  }
}

export {
  FilesService,
  FilesModel,
  Result,
  ICache,
  Services,
  ArticleModel,
  ArticleService
}
